package com.example.lenovo.asia5b.my.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatRadioButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.example.lenovo.asia5b.home.bean.RegionBean;
import com.example.lenovo.asia5b.my.bean.AddressBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;
import static com.wushi.lenovo.asia5b.R.id.public_btn_left;

/**
 * //添加收货地址
 */


public class EditAddressActivity extends BaseActivity  implements ICallBack {
    private AppCompatRadioButton rad_is_default ;
    private List<RegionBean> lists;
    private List<String> listNameOnes;
    private String country,province;
    private Spinner spr_country,spr_province;
    private LoadingDalog loadingDalog;
    private AddressBean bean;
    private int country_2_id,province_id;
    //一开始使用
    private boolean isOne;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_address);
        initView();
        regionList();
    }

    private void initView(){
        loadingDalog = new LoadingDalog(EditAddressActivity.this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.bjshdz));

        rad_is_default = (AppCompatRadioButton)findViewById(R.id.rad_is_default);
        spr_country = (Spinner)findViewById(R.id.spr_country);
        spr_province = (Spinner)findViewById(R.id.spr_province);
        F.id(R.id.btn_add).clicked(this);
        F.id(public_btn_left).clicked(this);
        if (getIntent().hasExtra("bean")) {
            bean = (AddressBean)getIntent().getSerializableExtra("bean");
            F.id(R.id.edit_email).text(bean.city);
            F.id(R.id.edit_address).text(bean.address);
            if (bean.is_default.equals("1")) {
                rad_is_default.setChecked(true);
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case public_btn_left:
                finish();
                break;
            case R.id.btn_add:
                addData();
                break;
        }
    }

    /**
     * 添加地址
     */
    public void addData() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.UPDA_RESS;
        String user_id = getUserBean().user_id;
        //国家ID
        String  country =this.country;
        //州ID
        String  province = this.province;
        //邮编
        String city = F.id(R.id.edit_email).getText().toString();
        //详细地址
        String address =  F.id(R.id.edit_address).getText().toString();
        //设置默认
        String is_default = "0";
        //1为默认
        if (rad_is_default.isChecked()) {
            is_default = "1";
        }
        //判断条件
        if (TextUtils.isEmpty(province)) {
            U.Toast(EditAddressActivity.this,getResources().getString(R.string.add_address_hint_3));
        }else if (TextUtils.isEmpty(city)) {
            U.Toast(EditAddressActivity.this,getResources().getString(R.string.add_address_hint_4));
        }  else if (TextUtils.isEmpty(address)) {
            U.Toast(EditAddressActivity.this, getResources().getString(R.string.add_address_hint_1));
        }else {
            try {
                loadingDalog.show();
                Date date = new Date();
                String time = String.valueOf(date.getTime());
                String[] sort = {"user_id" + user_id, "type"+1,"is_default"+is_default, "time" + time};
                String sortStr = Logic.sortToString(sort);
                String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                parmaMap.put("user_id", user_id);
                parmaMap.put("type", 1+"");
                parmaMap.put("country", country);
                parmaMap.put("province", province);
                parmaMap.put("city", city);
                parmaMap.put("address", address);
                parmaMap.put("is_default", is_default);
                parmaMap.put("time", time);
                parmaMap.put("sign", md5_32);
                if (null !=bean ) {
                    parmaMap.put("address_id", bean.address_id);
                }
                JsonTools.getJsonAll(this, url, parmaMap, 1);
            } catch (Exception e) {

            }
        }

    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int)json.getInt("State");
                        if (state == 0) {
                            JSONArray title = json.getJSONArray("region");
                            lists = Logic.getListToBean(title, new RegionBean());
                            showAddress();
                        }else if(state == 1){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.qmsb)
                            );
                        }else if(state == 2){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.cscw)
                            );
                        }
                    } catch (Exception e) {
                    }
                }
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int)json.getInt("State");
                        if(state == 0) {
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.bjcg));
                            Intent intent = new Intent();
                            intent.putExtra("22","22");
                            EditAddressActivity.this.setResult(0, intent);
                            finish();
                        }else if(state == 1){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.qmsb));
                        }else if(state == 2){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.cscw));
                        }else if(state == 3){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.add_address_hint_1));
                        }else if(state == 4){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.sjhbnwk));
                        }else if(state == 5){
                            U.Toast(EditAddressActivity.this,getResources().getString(R.string.wdl));
                        }

                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
        }
    };


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    //国家/州选择器
    public void showAddress() {
        getPriovince();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(EditAddressActivity.this,
                R.layout.simple_list_item,
                listNameOnes);
        spr_country.setAdapter(adapter1);
        spr_country.setSelection(country_2_id);
        spr_country.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                final RegionBean bean =  lists.get(arg2);
                country = bean.region_id;
                List<String> citys = getBanks(bean);
                ArrayAdapter<String> adapter2=new ArrayAdapter<String>(EditAddressActivity.this,
                        R.layout.simple_list_item,
                        citys);
                spr_province.setAdapter(adapter2);
                if (!isOne) {
                    //这里只调用一次
                    spr_province.setSelection(province_id);
                    isOne = true;
                }
                spr_province.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        province = bean.chile.get(arg2).region_id;
                    }
                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });

    }

    //  通过遍历集合获得银行的名字 --备用赋值给Spinner1
    private void getPriovince(){
        listNameOnes=new ArrayList<String>();
        for (int i = 0; i <lists.size(); i++) {
            RegionBean bean = lists.get(i);
            String cityname = bean.region_name;
            listNameOnes.add(cityname);
            if (null != this.bean) {
                if (this.bean.country_2_id.equals(bean.region_id)){
                    country_2_id = i;
                }
            }
        }
    }

    //  通过市获得区--备用赋值给Spinner2
    private List<String> getBanks(RegionBean bean){
        List<String> listBankNameTwos=new ArrayList<String>();
        List<RegionBean> citys = bean.chile;
        for (int i = 0; i <citys.size(); i++) {
            RegionBean citys2  =citys.get(i);
            String cityName = citys2.region_name;
            listBankNameTwos.add(cityName);
            if (null != this.bean) {
                if (this.bean.province_id.equals(citys2.region_id)){
                    province_id = i;
                }
            }
        }
        return listBankNameTwos;
    }
    /**
     * 地址名称接口
     */
    public void regionList() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.REGION_LIST;
        JsonTools.getJsonAll(this, url, parmaMap, 0);
    }
}
